//
//  MQUserAccountViewModel.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/18.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class MQUserAccountViewModel: NSObject {
    
    var userAccount:MQUserAccount?
    //单例
    static let shareUserAccountViewModel:MQUserAccountViewModel = MQUserAccountViewModel()
    
    override init() {
        super.init()
        userAccount = getUserAccount()
    }
    
    var isUserLogin:Bool{
        if accessToken != nil && isExpiresIn == false{
            return true
        }
        return false
    }
    
    var isExpiresIn:Bool{
        //获取过期时间
        if let expiresData = userAccount?.expiresDate{
            
            //测试
//            expiresData = NSDate().dateByAddingTimeInterval(-1)
            
            //获取当前时间
            let nowDate = NSDate()
            
            //对比,升序代表没过期，返回false
            if nowDate.compare(expiresData) == .OrderedAscending{
                return false
            }
        }
        
        return true
    }
    
    var accessToken: String?{
        return userAccount?.access_token
    }
    
    //archivePath
    private let archivePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString) .stringByAppendingPathComponent("userInfo.archive")
    
    //获取访问令牌
    func loadAccessToken(code:String, complete: (isSuccess: Bool)->()){
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            /*
            client_id	true	string	申请应用时分配的AppKey。
            client_secret	true	string	申请应用时分配的AppSecret。
            grant_type	true	string	请求的类型，填写authorization_code
            
            grant_type为authorization_code时
            必选	类型及范围	说明
            code	true	string	调用authorize获得的code值。
            redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
            */
            "client_id" : WB_APPKEY,
            "client_secret" : WB_APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : WB_REDIRECT_URI
        ]
        
        MQNetWorkTools.sharedTools.request(MQRequestMethod.POST, urlString: url, parameters: params) { (response, error) -> () in
            if error != nil{
                printfLog(error)
                complete(isSuccess: false)
            }
            //
            //            printfLog(response)
            guard let dict = response as? [String : AnyObject] else{
                printfLog("获取的数据不是字典")
                complete(isSuccess: false)
                return
            }
            
            let account = MQUserAccount(dict: dict)
            printfLog(account)
            self.loadUserAccount(account, complete: complete)
        }
        
    }
    
    //获取用户信息
    func loadUserAccount(account:MQUserAccount, complete:(isSuccess:Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        MQNetWorkTools.sharedTools.request(MQRequestMethod.GET,urlString: urlString, parameters: params) { (response, error) -> () in
            if error != nil{
                printfLog("未获取到用户数据")
                printfLog(error)
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else{
                printfLog("获取的数据不是字典")
                complete(isSuccess: false)
                return
            }
            
            account.avatar_lager = dict["avatar_lager"] as? String
            account.screen_name = dict["screen_name"] as? String
            
            self.userAccount = account
            //保存用户信息
            self.saveAccount(account)
            
            complete(isSuccess: true)
            
        }
    }
}
// MARK: - 归档解档用户信息
extension MQUserAccountViewModel{
    func saveAccount(account:MQUserAccount){
        NSKeyedArchiver.archiveRootObject(account, toFile: archivePath)
    }
    
    func getUserAccount() -> MQUserAccount?{
        return NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? MQUserAccount
    }
}
